const mongoose = require('mongoose');
const Product = require('../models/product.model');
exports.create = function(req, res, next) {
    const product = new Product(req.body);
    product.save().then((data) => res.json(data));

}
exports.update = function(req, res, next) {
    const id = req.params.id;
    Product.findByIdAndUpdate(id, {
        $set: req.body
    }, {
        new: false
    }).then(data => {
        res.json(data);
    });
}
exports.remove = function(req, res, next) {
    const id = req.params.id;
    console.log(id);
    Product.findByIdAndDelete(id, (err, data) => {
        res.json(data);
    });
}
exports.removes = function(req, res, next) {
    const ids = req.body.ids.split(',');
    console.log(ids);
    if (ids.length > 0) {
        Product.remove({
            _id: {
                $in: ids
            }
        }).then(data => {
            res.json({
                "message": "数据已删除!"
            })
        })
    }
}
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 10;
    var queryCondition = {};
    if (req.body.goodsname && req.body.goodsname.trim().length > 0) {
        queryCondition = {
            "goodsname": new RegExp(req.body.goodsname, 'i')
        }
    }
    if (req.body.productId && req.body.productId.trim().length > 0) {
        queryCondition = {
            "productId": req.body.productId
        }
    }
    Product.paginate(queryCondition, {
        page: +page,
        limit: +limit
    }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}
exports.get = function(req, res, next) {
    const id = req.params.id;
    Product.findById(id).then(data => {
        res.json(data);
    })
}